<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言在Node.js中，所有函数都是异步得，性能虽然好，但是容易造成回调地狱。在Node中，为解决API级别得回调地狱问题，引入了用于流程控制得部分：异步流程控制。 在异步流程控制方面做出得结果有以下：1、Thunk、Promise&#x2F;A+规范落地；2、在ES6中支持Generator与co模块；3、async函数。 异步调用Ajax和Node是两种典型得异步实现方案：Ajax的核心是XMLHttp">
<meta property="og:type" content="article">
<meta property="og:title" content="异步与async">
<meta property="og:url" content="http://example.com/2021/10/19/node/%E5%BC%82%E6%AD%A5%E4%B8%8Easync/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言在Node.js中，所有函数都是异步得，性能虽然好，但是容易造成回调地狱。在Node中，为解决API级别得回调地狱问题，引入了用于流程控制得部分：异步流程控制。 在异步流程控制方面做出得结果有以下：1、Thunk、Promise&#x2F;A+规范落地；2、在ES6中支持Generator与co模块；3、async函数。 异步调用Ajax和Node是两种典型得异步实现方案：Ajax的核心是XMLHttp">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-19T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-05T08:36:29.814Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="node狼书">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/10/19/node/%E5%BC%82%E6%AD%A5%E4%B8%8Easync/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>异步与async | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/19/node/%E5%BC%82%E6%AD%A5%E4%B8%8Easync/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          异步与async
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-10-19 12:18:39" itemprop="dateCreated datePublished" datetime="2021-10-19T12:18:39+08:00">2021-10-19</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-05 16:36:29" itemprop="dateModified" datetime="2021-11-05T16:36:29+08:00">2021-11-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>在Node.js中，所有函数都是异步得，性能虽然好，但是容易造成回调地狱。在Node中，为解决API级别得回调地狱问题，引入了用于流程控制得部分：异步流程控制。</p>
<p>在异步流程控制方面做出得结果有以下：1、Thunk、Promise/A+规范落地；2、在ES6中支持Generator与co模块；3、async函数。</p>
<h1 id="异步调用"><a href="#异步调用" class="headerlink" title="异步调用"></a>异步调用</h1><p>Ajax和Node是两种典型得异步实现方案：Ajax的核心是XMLHttpRequest对象，Node.js的核心是EventLoop。</p>
<p>Ajax定义好请求和回调函数后，剩下的事情就交由XHR处理，XHR与服务器交互会产生时间差异，所以异步操作能很好解决该问题。</p>
<p>Node.js异步的核心是EventLoop，我们调用Node.jsAPI方法时，它会将具体操作和回调函数交给EventLoop来执行，而EventLoop维护了一个回调函数队列，异步函数执行时，回调函数会被放入这个队列，JS引擎直到异步函数执行完成后，才会开始处理EventLoop。</p>
<p>EventLoop是用C++编写的libuv库，其采用了异步和事件驱动的编程风格，主要功能是为开发人员提供一套基于I/O通知的回调函数，实际上是由操作系统处理的。</p>
<p>综上所述，无论Ajax还是Node，其都是借助中间层来进行实际操作的，我们无序过多关注底层就可以简单地完成功能开发。</p>
<h2 id="简单实践"><a href="#简单实践" class="headerlink" title="简单实践"></a>简单实践</h2><p>这里我们简单写一个找出以KOA开头的文件的函数，这里会用到fs.readdir(path, callback)，这样一个API。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//异步写法如下：</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="string">'.'</span>;</span><br><span class="line"></span><br><span class="line">fs.readdir(path, <span class="function"><span class="keyword">function</span> (<span class="params">err, files</span>) </span>&#123;</span><br><span class="line">   files.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">file</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (<span class="regexp">/^koa/</span>.test(file)) &#123;</span><br><span class="line">           <span class="built_in">console</span>.log(file);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;); </span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//在上例中，获取文件的结果是在回调函数中实现的，很明显为异步写法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//同步写法如下：</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> files = fs.readdirSync(<span class="string">'.'</span>)</span><br><span class="line">files.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">file</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="regexp">/^koa/</span>.test(file)) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(file);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//在同步写法中，首先获取文件结果，然后遍历文件并打印结果。</span></span><br></pre></td></tr></table></figure>

<h2 id="事件处理"><a href="#事件处理" class="headerlink" title="事件处理"></a>事件处理</h2><p>Node中有两种事件处理方式，分别是回调和事件发射器。callback使用错误优先的回调方式，而事件发射器则是事件驱动里的事件发射。</p>
<h3 id="错误优先"><a href="#错误优先" class="headerlink" title="错误优先"></a>错误优先</h3><p>定义错误优先的回调方式只需要注意两条规则：1、回调函数的第一个参数返回的是error对象，若发生错误，则该对象会作为第一个参数返回；2、回调函数的第二个参数返回的是所有成功响应的结果数据。结果正常时，error就会被设置为null，在第二个参数处返回正确的响应。</p>
<p>模块应该暴露错误优先的回调接口，且应该经常在回调中检查错误。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">readJSON</span>(<span class="params">filePath, callback</span>) </span>&#123;</span><br><span class="line">    fs.readFile(filePath, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> parsedJson;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//处理错误，我们总是要在回调函数中处理错误，这是不可或缺的。</span></span><br><span class="line">        <span class="keyword">if</span>(err) &#123;</span><br><span class="line">            <span class="keyword">return</span> callback(err);</span><br><span class="line">            <span class="comment">//当发生错误时，使用return，让程序在if语句中停止执行</span></span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//解析JSON</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//使用try-catch来捕获同步函数中的异常</span></span><br><span class="line">            parsedJson = <span class="built_in">JSON</span>.parse(data);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (exception) &#123;</span><br><span class="line">            <span class="keyword">return</span> callback(exception);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//只有一切正常时，则直接调用回调函数</span></span><br><span class="line">        <span class="keyword">return</span> callback(<span class="literal">null</span>, parsedJson);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="事件发射"><a href="#事件发射" class="headerlink" title="事件发射"></a>事件发射</h3><p>事件模块是Node.js内置的对观察者模式的实现，通过EventEmitter属性提供一个构造函数，该构造函数的实例中有两个常用方法，其中on方法用来监听指定事件，并触发回调函数；emit方法用于发布事件。</p>
<p>events模块只提供了一个对象：events.EventEmitter；其核心部分就是对事件触发与实践监听器功能的封装。</p>
<p>默认时，Node.js允许同一个实践最多指定10个回调函数，超过时会发出警告，需要用setMaxListeners方法修改最大监听数。</p>
<p>1、事件操作：events模块默认支持以下：newListener事件与removeListener事件，分别在新增、删除回调函数时触发。</p>
<p>2、once方法，与on类似，但回调函数只会被触发一次。</p>
<p>3、获取监听器信息：通过listeners方法实现，该方法接收一个事件名称作为参数，返回由该事件所有回调函数组成的数组。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">'events'</span>);</span><br><span class="line"><span class="keyword">const</span> emitter = <span class="keyword">new</span> EventEmitter();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">onlyOnce</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(ee.listeners(<span class="string">"firstConnection"</span>));</span><br><span class="line">    ee.removeListener(<span class="string">"firstConnection"</span>, onlyOnce);</span><br><span class="line">    <span class="built_in">console</span>.log(ee.listeners(<span class="string">"firstConnection"</span>));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ee.on(<span class="string">"firstConnection"</span>, onlyOnce);</span><br><span class="line">ee.emit(<span class="string">"firstConnection"</span>);</span><br><span class="line">ee.emit(<span class="string">"firstConnection"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//以上代码显示两次由回调函数组成的数组，第一次只有onlyOnce，第二次由于已经remove，因此为空数组</span></span><br><span class="line"><span class="comment">//[[Function: onlyOnce]]</span></span><br><span class="line"><span class="comment">//[]</span></span><br></pre></td></tr></table></figure>

<p>4、事件错误处理：方式与常规函数一致，即在回调函数里判断error参数，同时结合Event中最常用的on方法来监听error事件。</p>
<p>为什么http.get方法可以用on来进行错误处理呢：</p>
<p>http.get方法本质是用request来请求的 =》request方法是ClientRequet中实现的，基于Stream =》 而Stream是继承字events的。</p>
<p>http模块是Node的核心模块，Stream是核心中核心，而events就是底层基础，为核心代码服务。</p>
<p>回调与事件的选择问题：</p>
<p>API推荐优先使用错误优先的回调方式，统一使用SDK的回调风格；在同一对象内，则用EventEmitter解耦。可以合理地利用集成。</p>
<h1 id="回调处理"><a href="#回调处理" class="headerlink" title="回调处理"></a>回调处理</h1><h2 id="Thunk"><a href="#Thunk" class="headerlink" title="Thunk"></a>Thunk</h2><p>Thunk函数：JS采用的是“传名调用”的参数求职策略，即将参数放在一个临时函数之中，再将这个临时函数传入函数体，这个临时函数就叫做Thunk函数。在co应用中，为编写与同步一样的异步代码，比较常见的就是用Thunk函数。</p>
<h2 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h2><h2 id="Generator"><a href="#Generator" class="headerlink" title="Generator"></a>Generator</h2><p>Generator函数和Generator是ES6新加入的特性，其本质上是一种特殊的迭代器。Generator本意是Iterator生成器，函数运行到yield时退出，并保留上下文，在下次进入时可以继续运行。生成器函数也是一种哈桑农户，语法上仅比普通函数多了一个“*”，其函数体内部可以使用yield和yield关键字。</p>
<p>由于Generator函数返回的遍历器对象只有调用next方法才会遍历下一个内部状态，其yield语句就是暂停标志。遍历器对象的next方法运行逻辑如下：</p>
<p>1、遇到yield语句就暂停执行后面的操作，并将紧跟在yield后的表达式值作为返回的对象的value属性值。</p>
<p>2、下一次调用next方法时，再继续往下执行，直到遇到下一条yield语句。</p>
<p>3、如果没有再遇到新得yield语句，就一直运行到函数结束，直到return语句位置，并将return语句后的表达式值作为返回对象的value属性值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//实例代码如下，Generator是生成器，需要先生成对象才能继续执行。</span></span><br><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">doSomething</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'1'</span>);</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">'1'</span>;<span class="comment">//Line(A);</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'2'</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> gen = doSomething();</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> a = gen1.next();</span><br><span class="line"><span class="comment">//a为&#123;value:'1',done:false&#125;;打印出1，然后代码悬停至Line(A)处</span></span><br><span class="line"><span class="keyword">let</span> b = gen1.next();</span><br><span class="line"><span class="comment">//b为&#123;value:'',done:true&#125;;done为true时，代表generator里的异步操作均执行完；会打印出2.</span></span><br></pre></td></tr></table></figure>

<p>co模块是为了能够在generator中使用多个yield，co是ES6generator的执行其，但不能与async函数混用，返回的结果是Promise对象。</p>
<p>co适用于调用generator的场景。在async函数中，await关键字后可以接Promise，co的返回值是Promise。</p>
<p>co的典型用法是作为generator的执行器使用：1、co是generator执行器，因此只要管好yield即可，不用关心generator是怎么执行的；2、co的返回值是Promise，后面可以直接接Promise的then函数。</p>
<p>co的简单源码如下：</p>
<h2 id="async函数"><a href="#async函数" class="headerlink" title="async函数"></a>async函数</h2><p>generator的弊病是没有执行器，因此要借助co。但一直借助外部模块不是办法，因此，async/await就被创造出来了。async函数是什么？其实它的本质就是Generator函数的语法糖。</p>
<p>async函数返回一个promise对象，可以使用then方法添加回调函数，当函数执行的时候，一旦遇到await就会先返回，等到异步操作完成，再接着执行函数体内后面的语句。同样，async函数内部return语句返回的值，会成为then方法回调函数的参数。同样，async函数内部抛出错误会导致返回的promise对象变为reject状态，该错误会被catch方法回调函数接收到。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">getStockPriceByName</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> symbol = <span class="keyword">await</span> getStockSymbol(name);</span><br><span class="line">    <span class="keyword">var</span> stockPrice = <span class="keyword">await</span> getStockPrice(symbol);</span><br><span class="line">    <span class="keyword">return</span> stockPrice;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">getStockPriceByName(<span class="string">'goog'</span>).then(<span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//调用该函数会在查询完之后，打印查询结果，同时不影响同步进程。</span></span><br></pre></td></tr></table></figure>

<p>async函数返回的Promise对象必须等到内部所有await命令后面的promise对象执行完才会发生状态改变，除非遇到return语句或者抛出错误。也就是说，只有async函数内部的异步操作执行完，才会执行then方法指定的回调函数。</p>
<p>async的执行过程示例代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//async的执行过程</span></span><br><span class="line">exports.list = <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> students = <span class="keyword">await</span> Student.getAllAsync();</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">await</span> ctx.render(<span class="string">'students/index'</span>, &#123;</span><br><span class="line">            students : students</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">        <span class="keyword">return</span> ctx.api_error(err);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">以上代码完成了三个操作：</span></span><br><span class="line"><span class="comment">1、通过await Student.getAllAsync()，获取所有的student信息</span></span><br><span class="line"><span class="comment">2、通过await ctx.render渲染页面</span></span><br><span class="line"><span class="comment">3、由于是同步代码，用try,catch进行异常处理。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>正常情况下，await命令后是一个Promise对象，如果不是，会被转成一个立即resolve的Promise对象。</p>
<p>错误处理：如果await后面的异步操作出错，那么等同于async函数返回的Promise对象被reject。而防止出错的方法是：将其放在try…catch代码块中，如果有多个await命令，则可以统一放在try…catch结构中。</p>
<p>await的三种用法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//await+async函数的实例代码如下</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//await+Promise用法如下：</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//await+co+Generator用法如下：</span></span><br></pre></td></tr></table></figure>

<p>上面三种用法的要点如下：1、co的返回值是Promise，所以await可以和co直接连接使用；2、co的参数是Generator；3、在Generator里可以使用yield。</p>
<p>async函数的要点如下：1、async函数本身具有执行能力，不用像generator一样借助co；2、async进行异常处理时，可以用try-catch或者Promise的处理方式；3、async后接Promise，Promise自身可应对所有流程，并可用all和race来补齐并行处理机制；4、await+promise可以覆盖所有应用场景。</p>
<h3 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h3><p>对于async函数来说，其await语句是同步执行的，所以最正常的流程处理需要采用try-catch，这与generator函数一样。</p>
<p>在常见的WEB应用中，总结的实践经验是：DAO层用Promise比较好，而Service层用async函数更好。DAO层使用Promise基本只需要几层代码，一般单一模型的操作不会太复杂，而Service层则一般针对多模型进行操作，可拆分成多个简单操作，然后用await进行组合。</p>
<h3 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h3><p>async函数的原理就是将generator函数和自动执行器包装在一个函数中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params">args</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//等同于</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params">args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> spawn(<span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="comment">//...</span></span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//其中的spawn函数就是自动执行器，下面写出它的简单实现。</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">spawn</span>(<span class="params">genF</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> gen = genF();</span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">step</span> (<span class="params">nextF</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">var</span> next = nextF();</span><br><span class="line">            &#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">                <span class="keyword">return</span> reject(e);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (next.done) &#123;</span><br><span class="line">                <span class="keyword">return</span> resolve(next.value);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">Promise</span>.resolve(next.value).then(<span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">                step(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> gen.next(v);</span><br><span class="line">                &#125;)</span><br><span class="line">            &#125;, <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> gen.throw(e); </span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        step(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> gen.next(<span class="literal">undefined</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>至此，狼书第一本总结完毕，开始看狼书第二本。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/10/19/node/%E5%BC%82%E6%AD%A5%E4%B8%8Easync/" title="异步与async">http://example.com/2021/10/19/node/异步与async/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/node%E7%8B%BC%E4%B9%A6/" rel="tag"># node狼书</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/14/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/elementUI%E4%BD%BF%E7%94%A8%E9%81%BF%E5%9D%91/" rel="prev" title="elementUI使用避坑">
      <i class="fa fa-chevron-left"></i> elementUI使用避坑
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/10/20/node/Koa%E6%A1%86%E6%9E%B6%E5%85%A5%E9%97%A8/" rel="next" title="koa框架入门">
      koa框架入门 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#异步调用"><span class="nav-number">2.</span> <span class="nav-text">异步调用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#简单实践"><span class="nav-number">2.1.</span> <span class="nav-text">简单实践</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事件处理"><span class="nav-number">2.2.</span> <span class="nav-text">事件处理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#错误优先"><span class="nav-number">2.2.1.</span> <span class="nav-text">错误优先</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#事件发射"><span class="nav-number">2.2.2.</span> <span class="nav-text">事件发射</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#回调处理"><span class="nav-number">3.</span> <span class="nav-text">回调处理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Thunk"><span class="nav-number">3.1.</span> <span class="nav-text">Thunk</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise"><span class="nav-number">3.2.</span> <span class="nav-text">Promise</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Generator"><span class="nav-number">3.3.</span> <span class="nav-text">Generator</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#async函数"><span class="nav-number">3.4.</span> <span class="nav-text">async函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#异常处理"><span class="nav-number">3.4.1.</span> <span class="nav-text">异常处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#源码"><span class="nav-number">3.4.2.</span> <span class="nav-text">源码</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

